#include "EpilNumberManager.h"
#include "EpilInterpreter.h"
#include "EpilObjectHelper.h"
#include "EpilPointerHelper.h"


EpilNumberManager::EpilNumberManager( EpilInterpreter * interpreter )
: m_interpreter( interpreter )
{
	for( int i = 0; i < SmallNumberMax - SmallNumberMin + 1; i++ )
	{
		m_smallNumberPool[i] = new EpilNumberObject( interpreter, SmallNumberMin + i );
	}
}


EpilNumberManager::~EpilNumberManager()
{
	for( int i = 0; i < SmallNumberMax - SmallNumberMin + 1; i++ )
	{
		EpilPointerHelper::SafeDelete( m_smallNumberPool[i] );
	}
}


EpilNumberObject * EpilNumberManager::CreateNumberObject( double value )
{
	if( this->IsSmallNumber( value ) )
	{
		return this->CreateSmallNumber( value );
	}
	else
	{
		return this->CreateNormalNumber( value );
	}
}


void EpilNumberManager::ReleaseNumberObject( EpilNumberObject * obj )
{
	if( this->IsSmallNumber( obj->GetValue() ) )
	{
		this->ReleaseSmallNumber( obj );
	}
	else
	{
		this->ReleaseNormalNumber( obj );
	}
}


bool EpilNumberManager::IsSmallNumber( double value )
{
	if( EpilObjectHelper::IsDoubleGreaterThanOrEquals( value, SmallNumberMin ) &&
		EpilObjectHelper::IsDoubleLessThanOrEquals( value, SmallNumberMax ) )
	{
		if( EpilObjectHelper::IsInteger( value ) )
		{
			return true;
		}
	}
	return false;
}


EpilNumberObject * EpilNumberManager::CreateSmallNumber( double value )
{
	int num = static_cast<int>( value );
	return m_smallNumberPool[num - SmallNumberMin];
}


void EpilNumberManager::ReleaseSmallNumber( EpilNumberObject * obj )
{
}


EpilNumberObject * EpilNumberManager::CreateNormalNumber( double value )
{
	EpilNumberObject * ret = new EpilNumberObject( m_interpreter, value );
	return ret;
}


void EpilNumberManager::ReleaseNormalNumber( EpilNumberObject * obj )
{
	EpilPointerHelper::SafeDelete( obj );
}